<template>
  <div class="alarm-type-statistics">
    <div class="top-line">
      <div class="chart-container">
        <base-echart
          style="position: absolute;z-index: 888;"
          :show-no-data="true"
          :options="state.AlarmStatisticsOptions"
          height="200"
        ></base-echart>
        <div class="route"></div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import {
  reactive,
  ref,
  onMounted,
  nextTick,
  onUnmounted,
  defineProps,
  watch,
} from "vue";
import { AlarmStatisticsOptions } from "./config/config";
import { NewGeneral } from "@/api/screen/equipment";
import { useIds } from "@/stores/screen/ids";
import pLimit from "p-limit";
import emits from "@/utils/emits";
import { getGeneralValues } from "@/api/general";
const state = reactive<any>({ AlarmStatisticsOptions });
const { getsessionStorage } = useIds();
const codeData = [
  {
    name: "未处理",
    code: "AI_ALERT_MESSAGE_DETAIL_TODAY_UNDEAL_EVENT",
  },
  {
    name: "已处理",
    code: "AI_ALERT_MESSAGE_DETAIL_TODAY_DEAL_EVENT",
  },
];
const alertToday = ref();
const handleToday = ref();
let resData = [];
const initData = async () => {
  let reqData = [];
  codeData.forEach((item: any) => {
    reqData.push({
      code: item.code,
      params: { equipmentIds: getsessionStorage() },
    });
  });

  await getGeneralValues(reqData).then((res) => {
    resData = [];
    codeData.forEach((item: any) => {
      alertToday.value = res.data["AI_ALERT_MESSAGE_DETAIL_TODAY_DEAL_EVENT"]
        ? res.data["AI_ALERT_MESSAGE_DETAIL_TODAY_DEAL_EVENT"].data
        : 0;
      handleToday.value = res.data["AI_ALERT_MESSAGE_DETAIL_TODAY_UNDEAL_EVENT"]
        ? res.data["AI_ALERT_MESSAGE_DETAIL_TODAY_UNDEAL_EVENT"].data
        : 0;
      if (!res.data[item.code]) {
        resData.push({ name: item.name, value: 0 });
      } else {
        resData.push({ name: item.name, value: res.data[item.code].data });
      }
      let total =
        alertToday.value + handleToday.value > 0
          ? alertToday.value + handleToday.value
          : 0;
      console.log(total, "total+++");

      state.AlarmStatisticsOptions.title[0].subtext = total.toString();
      state.AlarmStatisticsOptions.series[0].data = resData;
      // chartsData.push(item.name)
    });
    // console.log(chartsData)
  });
};
const tabIndex = ref(0);
defineProps({
  showList: {
    type: Boolean,
    default: true,
  },
  showcharts: {
    type: Boolean,
    default: false,
  },
});

// 数据格式
interface Data {
  name: string;
  code: string;
  icon: string;
  color: string;
  undo: number;
  total: number;
  key: string;
  parentsKey: string;
  time: string;
}
interface Algorithm {
  key: string;
  color: string;
  value: number;
  algorithm_name: Array<Data>;
}
let thetypeofalgorithm = ref<Array<Algorithm>>([
  {
    key: "人员违规",
    algorithm_name: [
      {
        name: "安全帽检测",
        code: "HELMET",
        icon: "未戴安全帽",
        color: "rgba(0, 148, 255, 1)",
        undo: 0,
        total: 0,
        key: "",
        parentsKey: "人员违规",
        time: null,
      },
      {
        name: "反光衣检测",
        code: "REFLECTIVE_CLOTHING",
        icon: "未穿反光衣",
        color: "rgba(31, 108, 255, 1)",
        undo: 0,
        total: 0,
        key: "",
        parentsKey: "人员违规",
        time: null,
      },
      {
        name: "人员入侵检测",
        code: "REGIONAL_INTRUSION",
        icon: "人员入侵",
        color: "rgba(240, 229, 192, 1)",
        undo: 0,
        total: 0,
        key: "",
        parentsKey: "人员违规",
        time: null,
      },
      {
        name: "司机违规下车检测",
        code: "DRIVER_OUT_CAR",
        icon: "司机违规下车",
        color: "rgba(60, 229, 189, 1)",
        undo: 0,
        total: 0,
        key: "",
        parentsKey: "人员违规",
        time: null,
      },
      {
        name: "行人违规检测",
        code: "PERSON_SIDEWALK_INTRUSION",
        icon: "行人违规",
        color: "rgba(98, 237, 112, 1)",
        undo: 0,
        total: 0,
        key: "",
        parentsKey: "人员违规",
        time: null,
      },
      {
        name: "人员离岗检测",
        code: "LEAVING_POSITION",
        icon: "人员离岗",
        color: "rgba(235, 146, 14, 1)",
        undo: 0,
        total: 0,
        key: "",
        parentsKey: "人员违规",
        time: null,
      },
      {
        name: "操作员吸烟检测",
        code: "DRIVER_SMOKE",
        icon: "操作员吸烟",
        color: "rgba(222, 206, 152, 1)",
        undo: 0,
        total: 0,
        key: "",
        parentsKey: "人员违规",
        time: null,
      },
      {
        name: "操作员打电话检测",
        code: "DRIVER_CALLING_PHONE",
        icon: "操作员打电话",
        color: "rgba(178, 130, 85, 1)",
        undo: 0,
        total: 0,
        key: "",
        parentsKey: "人员违规",
        time: null,
      },
      {
        name: "人员违规吸烟检测",
        code: "SMOKE",
        icon: "吸烟",
        color: "rgba(255, 161, 93, 1)",
        undo: 0,
        total: 0,
        key: "",
        parentsKey: "人员违规",
        time: null,
      },
    ],
    color: "rgba(0, 148, 255, 1)",
    value: 0,
  },
  {
    key: "车辆违规",
    algorithm_name: [
      {
        name: "车辆占道检测",
        code: "SIDEWALK_INTRUSION",
        icon: "车辆占道",
        color: "rgba(255, 239, 92, 1)",
        undo: 0,
        total: 0,
        key: "",
        parentsKey: "车辆违规",
        time: null,
      },
      {
        name: "车辆调头检测",
        code: "TRUNAROUND",
        icon: "车辆调头",
        color: "rgba(255, 248, 189, 1)",
        undo: 0,
        total: 0,
        key: "",
        parentsKey: "车辆违规",
        time: null,
      },
      {
        name: "车辆违停检测",
        code: "NOPARKING",
        icon: "车辆违停",
        color: "rgba(115, 92, 255, 1)",
        undo: 0,
        total: 0,
        key: "",
        parentsKey: "车辆违规",
        time: null,
      },
      {
        name: "车辆逆行检测",
        code: "ANTIDROMIC",
        icon: "车辆逆行",
        color: "rgba(161, 146, 255, 1)",
        undo: 0,
        total: 0,
        key: "",
        parentsKey: "车辆违规",
        time: null,
      },
      {
        name: "车辆压线停车检测",
        code: "LINEBALL",
        icon: "车辆压线停车",
        color: "rgba(29, 178, 226, 1)",
        undo: 0,
        total: 0,
        key: "",
        parentsKey: "车辆违规",
        time: null,
      },
      {
        name: "车辆超速检测",
        code: "SPEED",
        icon: "车辆超速",
        color: "rgba(255, 172, 172, 1)",
        undo: 0,
        total: 0,
        key: "",
        parentsKey: "车辆违规",
        time: null,
      },
    ],
    color: "rgba(139, 215, 247, 1)",
    value: 0,
  },
  {
    key: "其它违规",
    algorithm_name: [
      {
        name: "烟火检测",
        code: "FIRE",
        key: "",
        icon: "烟火",
        color: "rgba(223, 67, 67, 1)",
        undo: 0,
        total: 0,
        parentsKey: "其它违规",
        time: null,
      },
    ],
    color: "rgba(255, 201, 64, 1)",
    value: 0,
  },
]);
// 百分比计算
const renderPercent = (percent: number) => {
  let total = 0;
  for (let i = 0; i < thetypeofalgorithm.value.length; i++) {
    total += thetypeofalgorithm.value[i].value;
  }
  // 四舍五入
  let finallyData = Math.round((percent / total) * 100);
  if (Object.is(finallyData, NaN)) {
    finallyData = 0;
  } else if (Object.is(finallyData, Infinity)) {
    finallyData = 100;
  }
  return finallyData;
};
// 告警数据
let alarmList = ref([
  {
    title: "已处理告警",
    color: "rgba(121, 246, 194, 1)",
    code: "AI_ALERT_MESSAGE_DETAIL_TODAY_DEAL_EVENT",
    value: 0,
  },
  {
    title: "未处理告警",
    color: "rgba(247, 110, 101, 1)",
    code: "AI_ALERT_MESSAGE_DETAIL_TODAY_UNDEAL_EVENT",
    value: 0,
  },
]);
// 告警数量未处理
const UNDEAL = async () => {
  // AI_ALERT_TODAY_UNDEAL_FOR_ALG告警数量未处理
  // 封装请求格式
  let config = [];
  thetypeofalgorithm.value.forEach((item) => {
    if (item.algorithm_name.length > 0) {
      item.algorithm_name.forEach((element, index) => {
        config.push({
          code: "AI_ALERT_TODAY_UNDEAL_TIME_FOR_ALG",
          key: `AI_ALERT_TODAY_UNDEAL_TIME_FOR_ALG_${element.code}`,
          params: {
            algCode: element.code,
            equipmentIds: getsessionStorage(),
          },
        });

        element.key = `AI_ALERT_TODAY_UNDEAL_TIME_FOR_ALG_${element.code}`;
      });
    }
  });
  // 数组对象去重
  config = config.filter((item, index, self) => {
    return (
      index ===
      self.findIndex((t) => {
        return t.params.algCode === item.params.algCode;
      })
    );
  });
  // 去重后格式请求
  if (config.length > 0) {
    let res = (await NewGeneral(config)) as any;
    if (res.code == 200) {
      // 判断对象是否为空
      if (Object.keys(res.data).length === 0) {
        return;
      }
      thetypeofalgorithm.value.forEach((item) => {
        if (item.algorithm_name.length > 0) {
          // 处理子集数据
          item.algorithm_name.forEach((element) => {
            // 查找和返回数据对象里的一样的值
            for (let resKey in res.data) {
              if (res.data[resKey].key === element.key) {
                element.undo = res.data[resKey].data.value;
                // 将获取的UTC字符串转换为北京时间
                element.time =
                  res.data[resKey].data.time == null
                    ? null
                    : new Date(
                        res.data[resKey].data.time
                      ).toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" });
              }
            }
          });
        }
      });
      // 按照时间进行排序从最新时间到最旧时间
      thetypeofalgorithm.value.forEach((item) => {
        if (item.algorithm_name.length > 0) {
          item.algorithm_name.sort((a, b) => {
            return new Date(b.time).getTime() - new Date(a.time).getTime();
          });
        }
      });
    }
  }
};
// 随机生成100以内的整数
const random = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1) + min);
};
const timer = ref(null);
// 告警数量统计
const TOTAL = async () => {
  if (timer.value) {
    clearInterval(timer.value);
  }

  // AI_ALERT_TODAY_FOR_ALG告警数量统计
  // 封装请求格式
  let seriesData = [];
  let config = [];
  let total = 0;
  thetypeofalgorithm.value.forEach((item) => {
    if (item.algorithm_name.length > 0) {
      item.algorithm_name.forEach((element, index) => {
        config.push({
          code: "AI_ALERT_TODAY_FOR_ALG",
          key: `AI_ALERT_TODAY_FOR_ALG${element.code}`,
          params: {
            algCode: element.code,
            equipmentIds: getsessionStorage(),
          },
        });
        element.key = `AI_ALERT_TODAY_FOR_ALG${element.code}`;
      });
    }
  });
  // 数组对象去重
  config = config.filter((item, index, self) => {
    return (
      index ===
      self.findIndex((t) => {
        return t.params.algCode === item.params.algCode;
      })
    );
  });
  // 去重后格式请求
  if (config.length > 0) {
    timer.value = setInterval(() => {
      thetypeofalgorithm.value.forEach((item, index) => {
        if (thetypeofalgorithm.value[index].value !== 0) {
          thetypeofalgorithm.value[index].value = random(1, 100);
        }
      });
    }, 1000);

    let res = (await NewGeneral(config)) as any;
    if (res.code == 200) {
      thetypeofalgorithm.value.forEach((item, index) => {
        thetypeofalgorithm.value[index].value = 0;
      });
      if (Object.keys(res.data).length === 0) {
        return;
      }
      clearInterval(timer.value);
      thetypeofalgorithm.value.forEach((item) => {
        // 父级数据先初始化
        if (item.algorithm_name.length > 0) {
          item.algorithm_name.forEach((element) => {
            // 查找和返回数据对象里的一样的值
            for (let key in res.data) {
              if (key === element.key) {
                element.total = res.data[key].data;
              }
            }

            // 处理父级告警统计数据
            if (item.key == element.parentsKey) {
              item.value += element.total;
            }
          });
        }
      });

      thetypeofalgorithm.value.forEach((item) => {
        total += item.value;
        seriesData.push({
          name: item.key,
          value: item.value,
        });
      });
      console.log(thetypeofalgorithm.value, "typeList");

      state.AlarmStatisticsOptions.series[0].data = seriesData;
      // state.AlarmStatisticsOptions.title[0].subtext = "" + total;
    }
  }
};
// 今日处理与未处理
// const getAlarmData = async () => {
//   let config = [];
//   alarmList.value.forEach((item) => {
//     config.push({
//       code: item.code,
//       params: {
//         equipmentIds: getsessionStorage(),
//       },
//     });
//   });
//   // 数组对象去重
//   config = config.filter((item, index, self) => {
//     return (
//       index ===
//       self.findIndex((t) => {
//         return t.code === item.code;
//       })
//     );
//   });

//   if (config.length > 0) {
//     let res = (await NewGeneral(config)) as any;
//     if (res.code == 200) {
//       if (Object.keys(res.data).length === 0) {
//         return;
//       }
//       alarmList.value.forEach((item) => {
//         for (let key in res.data) {
//           if (key == item.code) {
//             item.value = res.data[key].data;
//           }
//         }
//       });
//     }
//   }
// };

// const change = (index) => {
//   tabIndex.value = index;
// };
// 初始化
// const initData = () => {
//   //并发
//   const limit = pLimit(1);
//   //获取 首页3个统计数据
//   const input = [
//     limit(() => UNDEAL()),
//     limit(() => TOTAL()),
//     limit(() => getAlarmData()),
//   ];
//   Promise.all(input);
// };
// 创建一个轮询器
const PollingTimer = ref(null);
const PollingFunction = () => {
  if (PollingTimer.value) {
    clearInterval(PollingTimer.value);
  }
  PollingTimer.value = setInterval(() => {
    initData();
  }, 30000);
};
onMounted(() => {
  // 加载数据
  nextTick(() => {
    initData();
    PollingFunction();
    emits.on("HANDLE_MESSAGE", initData);
  });
});
// 销毁计时器
onUnmounted(() => {
  emits.off("HANDLE_MESSAGE", initData);
  if (PollingTimer.value) {
    clearInterval(PollingTimer.value);
  }
  clearInterval(timer.value);
});
</script>
<style lang="scss" scoped>
.alarm-type-statistics {
  width: 100%;
  height: 100%;
  padding-bottom: 0;
  box-sizing: border-box;
  position: relative;
  // 溢出
  // overflow-y: auto;
  // scrollbar-width: none;
  // -ms-overflow-style: none;

  // &::-webkit-scrollbar {
  //   display: none;
  //   /* Chrome Safari */
  // }
  @keyframes move {
    0% {
      transform: translate(-50%, -50%) rotate(0deg);
    }
    100% {
      transform: translate(-50%, -50%) rotate(360deg);
    }
  }

  .top-line {
    width: 100%;
    height: 100%;
    display: flex;
    // 两秒钟旋转一圈

    .chart-container {
      width: 100%;
      height: 100%;
      position: relative;
      .route {
        position: absolute;
        top: 50%;
        left: 50%;
        border-radius: 50%;
        transform: translate(-50%, -50%);
        border: 6px dotted rgba(14, 168, 235, 1);
        width: clamp(7.813rem, 6.51vw, 15.625rem);
        height: clamp(7.813rem, 6.51vw, 15.625rem);
        animation: move 10s linear infinite;
      }
    }

    .chart-data {
      width: 40%;
      height: 100%;

      display: flex;
      flex-direction: column;
      justify-content: center;

      .chart-data-item {
        width: 100%;
        height: 20%;
        margin-bottom: 10px;

        &:last-child {
          margin-bottom: 0;
        }

        .topic {
          width: 100%;
          height: 50%;
          display: flex;
          align-items: center;

          .title {
            font-size: clamp(0.875rem, 0.73vw, 1.75rem);
            color: rgba(207, 241, 255, 1);
          }

          .circle {
            width: 8px;
            height: 8px;
            border-radius: 2.5px;
            margin-right: 5px;
            background-color: rgba(0, 148, 255, 1);
          }
        }

        .data {
          width: 100%;
          height: 50%;
          display: flex;
          align-items: center;

          .text-number {
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: clamp(0.875rem, 0.73vw, 1.75rem);
            color: white;
            margin-left: 14px;
            margin-right: 5px;
          }

          .percent-number {
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: clamp(0.875rem, 0.73vw, 1.75rem);
            color: rgba(0, 148, 255, 1);
          }
        }
      }
    }
  }

  .alarm-container {
    width: 100%;
    height: fit-content;
    display: flex;
    margin-top: 20px;
    .list-tab {
      height: 100%;
      display: flex;
      justify-content: start;
      .tab-item {
        padding: clamp(0.5rem, 0.42vw, 1rem) clamp(0.938rem, 0.78vw, 1.875rem);
        color: rgba(136, 136, 136, 1);
        background-color: rgba(51, 51, 51, 0.6);
        border: 1px solid rgba(136, 136, 136, 1);
        box-sizing: border-box;
        cursor: pointer;
      }
      .currentIndex {
        color: rgba(38, 190, 255, 1);
        border-color: rgba(38, 190, 255, 1);
        background-color: rgba(15, 76, 102, 0.6);
      }
    }
    .alarm-item {
      width: 46%;
      height: 80%;

      display: flex;
      align-items: center;
      flex-direction: column;
      justify-content: center;
      background-color: rgba(8, 75, 128, 0.4);
      color: white;

      .title {
        font-size: clamp(1.125rem, 0.94vw, 2.25rem);
        font-weight: bold;
      }

      .number {
        font-size: clamp(1.75rem, 1.46vw, 3.5rem);
        font-family: Microsoft YaHei, Microsoft YaHei;
        font-weight: bold;
        color: #e2f2ff;
        letter-spacing: 2px;
        text-shadow: 0px 0px 6px #26beff;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  .type-list {
    width: 100%;
    height: auto;
    margin-top: clamp(1.875rem, 1.56vw, 3.75rem);
  }
  .alert-list {
    // margin-top: clamp(1.875rem, 1.56vw, 3.75rem);
  }
}
</style>
